﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Diagnostics;

namespace AutoRAR_dot_net
{
    class RARThread_C
    {
        private String myRARexePath { get; set; }
        private String myTargetPath { get; set; }
        private String mySize { get; set; }
        private String myPassword { get; set; }

        private Process rar { get; set; }

        private Thread rarIt { get; set; }

        public RARThread_C(String _RARexePath, String _TargetPath, String _Size, String _Password)
        {
            myRARexePath = _RARexePath;
            myTargetPath = _TargetPath;
            mySize = _Size;
            myPassword = _Password;

            rarIt = new Thread(new ThreadStart(startArchiving));
        }

        private void startArchiving()
        {
            DirectoryInfo directory = new DirectoryInfo(myTargetPath);

            rar = new Process();

            rar.StartInfo.FileName = myRARexePath;

            DirectoryInfo[] subdirectory = directory.GetDirectories();

            foreach (DirectoryInfo item in subdirectory)
            {
                rar.StartInfo.Arguments = "a -m5 -v" + mySize + " -hp" + myPassword + " -ep1 \"" + item.FullName + "\" \"" + item.FullName + "\"";
                rar.Start();
                rar.WaitForExit();
            }
        }

        public int start()
        {
            if (rarIt != null)
            {
                rarIt.Start();
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public int stop()
        {
            if (rarIt != null)
            {
                rar.Kill();
                rarIt.Abort();
                if (rarIt.IsAlive)
                {
                    return 0;
                }
                else
                {
                    return 1;
                }
            }
            else
            {
                return 1;
            }
        }

        public Boolean isRunning
        {
            get
            {
                return rarIt.IsAlive;
            }
        }
    }
}
